package com.android.launcher3;

import java.util.ArrayList;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.ViewFlipper;

/**
 * @author guoyisong
 * 
 *         底部 Option Menu 实现
 * 
 */
public class OptionMenu implements Menu {

	private PopupWindow popup;
	private GridView mGridView;
	private LinearLayout mLayout;
	private ViewFlipper mViewFlipper;
	private Context mContext;
	private int menuSize;

	/**
	 * 表示当前菜单页数,从 0 开始, 第一页为 0
	 */
	private int currentMenuPage;

	/**
	 * 保存所有菜单项
	 */
	private final static ArrayList<OptionMenuItem> mMenuItems = new ArrayList<OptionMenuItem>();
	/**
	 * 保存当前活动的菜单项
	 */
	private final static ArrayList<OptionMenuItem> mActiveMenuItems = new ArrayList<OptionMenuItem>();
	/**
	 * 保存当前页菜单项,每页显示8个菜单项,超出部分分页显示
	 */
	private static ArrayList<OptionMenuItem> mCurrentMenuItems = new ArrayList<OptionMenuItem>();

	public ArrayList<OptionMenuItem> getMenuItems() {
		return mCurrentMenuItems;
	}

	public GridView getMenuGridView() {
		return mGridView;
	}

	private ArrayList<OptionMenuItem> getCurrentMenuItems() {
		menuSize = getMenuSize();
		if (menuSize > 8) {
			mCurrentMenuItems = new ArrayList<OptionMenuItem>(
					mActiveMenuItems.subList(currentMenuPage * 7,
							(currentMenuPage * 7 + 7) > menuSize ? menuSize
									: currentMenuPage * 7 + 7));
			final int size = mCurrentMenuItems.size();
			if ((currentMenuPage * 7 + 7) < menuSize) {
				OptionMenuItem omi = new OptionMenuItem(mContext);
				omi.setTitle(R.string.menu_next)
						.setIcon(R.drawable.ic_menu_add).setVisible(true);
				mCurrentMenuItems.add(omi);
				currentMenuPage++;
			} else {
				for (int i = 0; i < (4 - size % 4 - 1); i++) {
					mCurrentMenuItems.add(new OptionMenuItem(mContext));
				}
				OptionMenuItem omi = new OptionMenuItem(mContext);
				omi.setTitle(R.string.menu_back)
						.setIcon(R.drawable.ic_menu_add).setVisible(true);
				mCurrentMenuItems.add(omi);
				currentMenuPage = 0;
			}
		} else {
			mCurrentMenuItems = mActiveMenuItems;
		}
		return mCurrentMenuItems;
	}

	private int getMenuSize() {
		int size = mMenuItems.size();
		mActiveMenuItems.clear();
		for (OptionMenuItem item : mMenuItems) {
			if (item.isVisible()) {
				mActiveMenuItems.add(item);
			} else {
				size--;
			}
		}
		return size;
	}

	private void changeMenuItems() {
		getCurrentMenuItems();
		mGridView.setAdapter(new MenuAdapter());
	}

	public OptionMenu(Launcher context) {
		initPopupMenu(context);
		mMenuItems.clear();
		mCurrentMenuItems.clear();
		mActiveMenuItems.clear();
	}

	/**
	 * 创建Popup Menu菜单
	 */
	private void initPopupMenu(final Launcher context) {
		mContext = context;
		// 创建动画
		mViewFlipper = new ViewFlipper(context);
		mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(context,
				R.anim.menu_in));
		mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(context,
				R.anim.menu_out));
		mLayout = new LinearLayout(context);
		mLayout.setOrientation(LinearLayout.VERTICAL);

		// 子选项栏
		mGridView = new GridView(context);
		mGridView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT));

		mGridView.setSelector(R.drawable.menu_item_selector);
		// mGridView.setNumColumns(4);
		mGridView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
		mGridView.setVerticalSpacing(0);
		mGridView.setHorizontalSpacing(0);
		mGridView.setPadding(4, 4, 4, 4);
		mGridView.setGravity(Gravity.CENTER);

		mGridView.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_MENU) {
					if (popup != null) {
						if (popup.isShowing()) {
							popup.dismiss();
						}
					}
				}
				return false;
			}
		});

		mGridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long id) {
				close();
				switch (position) {
				case 3:
					// 下一页 or 返回
					if (mCurrentMenuItems.size() == 4) {
						changeMenuItems();
						return;
					}
					break;
				case 7:
					// 下一页 or 返回
					if (menuSize > 8) {
						changeMenuItems();
						return;
					}
					break;
				default:
					break;
				}
				OptionMenuItem item = mCurrentMenuItems.get(position);
				if (null != item.getIntent()) {
					mContext.startActivity(item.getIntent());
				}
				context.onOptionsItemSelected(item);
			}
		});

		mLayout.addView(mGridView);
		mViewFlipper.addView(mLayout);
		mViewFlipper.setFlipInterval(60000);

		// 创建Popup
		popup = new PopupWindow(mViewFlipper, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);

		// 设置menu菜单背景
//		popup.setBackgroundDrawable(getResources().getDrawable(
//				R.drawable.menu_bg));
		popup.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FEC0C0C0")));

		popup.setAnimationStyle(android.R.style.Animation_InputMethod);

		// menu菜单获得焦点 如果没有获得焦点menu菜单中的控件事件无法响应
		popup.setFocusable(true);
		popup.update();

		popup.setOnDismissListener(new OnDismissListener() {
			public void onDismiss() {
				currentMenuPage = 0;
				menuSize = 0;
			}
		});
	}

	public void onMenuOpened(View viewParent) {
		getCurrentMenuItems();
		try {
			int mSize = mCurrentMenuItems.size();
			if (mSize > 0) {
				if (mSize < 4) {
					mGridView.setNumColumns(mCurrentMenuItems.size());
				} else {
					mGridView.setNumColumns(4);
				}
			}
			mGridView.setAdapter(new MenuAdapter());
			if (popup != null) {
				if (popup.isShowing()) {
					popup.dismiss();
				} else {
					popup.showAtLocation(viewParent, Gravity.BOTTOM, 0, 0);
					// 播放动画
					// mViewFlipper.startFlipping();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private final class MenuAdapter extends BaseAdapter {
		public int getCount() {
			return null == mCurrentMenuItems ? 0 : mCurrentMenuItems.size();
		}

		public Object getItem(int position) {
			if (null == mCurrentMenuItems) {
				return null;
			}
			return mCurrentMenuItems.get(position);
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (null == convertView) {
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.item_menu, null);
				holder = new ViewHolder();
				holder.text = (TextView) convertView
						.findViewById(R.id.item_text);
				holder.icon = (ImageView) convertView
						.findViewById(R.id.item_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.text.setText(mCurrentMenuItems.get(position).getTitle());
			holder.icon.setImageDrawable(mCurrentMenuItems.get(position)
					.getIcon());

			// convertView.setOnTouchListener(new OnTouchListener(){
			// public boolean onTouch(View view, MotionEvent event) {
			// if (event.getAction() == MotionEvent.ACTION_UP) {
			// view.setBackgroundColor(Color.parseColor("#DFC0C0C0"));
			// } else {
			// view.setBackgroundColor(Color.parseColor("#DF98FB98"));
			// }
			// return false;
			// }
			// });
			return convertView;
		}

		class ViewHolder {
			ImageView icon;
			TextView text;
		}
	}

	public OptionMenuItem add(CharSequence title) {
		OptionMenuItem omi = new OptionMenuItem(mContext);
		omi.setTitle(title);
		omi.setVisible(true);
		mMenuItems.add(omi);
		return omi;
	}

	public OptionMenuItem add(int titleRes) {
		return add(mContext.getString(titleRes)).setVisible(true);
	}

	public OptionMenuItem add(int groupId, int itemId, int order,
			CharSequence title) {
		OptionMenuItem omi = new OptionMenuItem(mContext, groupId, itemId,
				order, title);
		omi.setVisible(true);
		mMenuItems.add(omi);
		return omi;
	}

	public OptionMenuItem add(int groupId, int itemId, int order, int titleRes) {
		return add(groupId, itemId, order, mContext.getString(titleRes))
				.setVisible(true);
	}

	public int addIntentOptions(int groupId, int itemId, int order,
			ComponentName caller, Intent[] specifics, Intent intent, int flags,
			MenuItem[] outSpecificItems) {
		return 0;
	}

	public SubMenu addSubMenu(CharSequence title) {
		return null;
	}

	public SubMenu addSubMenu(int titleRes) {
		return null;
	}

	public SubMenu addSubMenu(int groupId, int itemId, int order,
			CharSequence title) {
		return null;
	}

	public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
		return null;
	}

	public void clear() {
		if (null != mMenuItems) {
			mMenuItems.clear();
		}
	}

	public void close() {
		if (popup != null) {
			if (popup.isShowing()) {
				popup.dismiss();
			}
		}
	}

	public OptionMenuItem findItem(int id) {
		if (null != mMenuItems) {
			for (OptionMenuItem item : mMenuItems) {
				if (id == item.getItemId()) {
					return item;
				}
			}
		}
		return null;
	}

	public OptionMenuItem getItem(int index) {
		if (null != mMenuItems) {
			return mMenuItems.get(index);
		}
		return null;
	}

	public boolean hasVisibleItems() {
		if (null != mMenuItems) {
			for (OptionMenuItem item : mMenuItems) {
				if (item.isVisible()) {
					return true;
				}
			}
		}
		return false;
	}

	public boolean isShortcutKey(int keyCode, KeyEvent event) {
		return false;
	}

	public boolean performIdentifierAction(int id, int flags) {
		return false;
	}

	public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
		return false;
	}

	public void removeGroup(int groupId) {
		if (null != mMenuItems) {
			ArrayList<OptionMenuItem> removeList = new ArrayList<OptionMenuItem>();
			for (OptionMenuItem item : mMenuItems) {
				if (item.getGroupId() == groupId) {
					removeList.add(item);
				}
			}
			mMenuItems.removeAll(removeList);
			removeList = null;
		}
	}

	public void removeItem(int id) {
		if (null != mMenuItems) {
			for (OptionMenuItem item : mMenuItems) {
				if (item.getItemId() == id) {
					mMenuItems.remove(item);
					break;
				}
			}
		}
	}

	public void setGroupCheckable(int group, boolean checkable,
			boolean exclusive) {

	}

	public void setGroupEnabled(int group, boolean enabled) {
		if (null != mMenuItems) {
			for (OptionMenuItem item : mMenuItems) {
				if (item.getGroupId() == group) {
					item.setEnabled(enabled);
				}
			}
		}
	}

	public void setGroupVisible(int group, boolean visible) {
		if (null != mMenuItems) {
			for (OptionMenuItem item : mMenuItems) {
				if (item.getGroupId() == group) {
					item.setVisible(visible);
				}
			}
		}
	}

	public void setQwertyMode(boolean isQwerty) {
	}

	public int size() {
		if (null != mMenuItems) {
			return mMenuItems.size();
		}
		return 0;
	}

}
